<template>
  <!-- 作业票执行 待验收 -->
  <view v-if="isEmpty">
    <empty></empty>
  </view>
  <view v-else style="padding-bottom: 300rpx">
    <view class="cu-card-wrap" v-for="(item, index) in listData" :key="item.nodeTaskId">
      <view class="header-wrap">
        <view class="title-wrap">
          <text class="title">{{ item.ticketCode }}</text>
        </view>
      </view>
      <view class="affix">
        <image
          class="affix-icon"
          :src="`/static/images/ticket-type/work-type-${item.workTypeFlag}.png`"
          mode="aspectFit"
        />
      </view>
      <view class="body-wrap">
        <view class="content-wrap">
          <view class="label">作业级别：</view>
          <view class="value">
            <view v-if="item.ticketWorkLevel" :class="styleSelector(item.ticketWorkLevel)">
              {{ item.ticketWorkLevelLabel }}</view
            >
            <view v-else>--</view>
          </view>
        </view>
        <view class="content-wrap">
          <view class="label">作业地点：</view>
          <view class="value">{{ item.workPoint }}</view>
        </view>
        <view class="content-wrap">
          <view class="label">作业内容：</view>
          <view class="value">{{ item.workContent }}</view>
        </view>
        <view class="content-wrap">
          <view class="label">作业票证：</view>
          <navigator :url="`/pages/jobSlip/detail/index?ticketId=${item.ticketId}`" class="value color-88B4C4">
            查看详情
            <image class="icon-more" src="/static/images/more.png"></image>
          </navigator>
        </view>
      </view>

      <view class="footer-wrap">
        <cu-dropdown v-if="item.assignee === staffId">
          <view class="more-button">更多</view>
          <template #dropdown>
            <cu-dropdown-item @click="showSignature(item)">新增作业人员</cu-dropdown-item>
            <template v-if="item.canPauseOrStart">
              <cu-dropdown-item v-if="item.pause === '2'" @click="goPage(item, 'pause')">暂停 </cu-dropdown-item>
              <cu-dropdown-item v-if="item.pause === '1'" @click="goPage(item, 'start')">启动 </cu-dropdown-item>
            </template>
          </template>
        </cu-dropdown>
        <view class="button-wrap">
          <view v-if="item.canAnalyse" class="button button-orange" @click="goInspect(item)">分析</view>
          <view v-if="item.assignee === staffId && item.pause === '2'" class="button" @click="goAcceptance(item)">
            验收
          </view>
        </view>
      </view>
    </view>

    <user-selector ref="userSelectorRef" @change="userSelectorChange"></user-selector>

    <Signature ref="signature" v-model="signatureUrl" auto-upload @success="onSignatureSuccess" />
  </view>
</template>

<script>
import { getAcceptTicketList, addWorkPersonal, updateGuardian } from '@/api/spw/ticketPerform.js'
import Empty from '@/components/cu-empty/index.vue'
import Signature from '@/pages/jobSlip/components/ContinueSign.vue'
import UserSelector from '@/components/user-selector/index.vue'
import CuDropdown from '@/components/cu-dropdown/index.vue'
import CuDropdownItem from '@/components/cu-dropdown/cu-dropdown-item.vue'
import { mapGetters } from 'vuex'
import { actNodePermissionEnum, specialWorkTypeEnum } from '@/utils/constant.js'
import { poiValid } from '../../../../api/spw/project'

export default {
  components: {
    Empty,
    UserSelector,
    Signature,
    CuDropdown,
    CuDropdownItem
  },
  computed: {
    ...mapGetters(['staffId']),
    isEmpty() {
      return this.isFinished && !this.listData.length
    }
  },
  beforeMount() {
    this.getlist()
    this.isPullDown(false)
  },
  data() {
    return {
      specialWorkTypeEnum,
      signatureUrl: '',
      textColor: true,
      listData: [],
      isFinished: false,
      loading: false,
      pageNum: 1,
      addPersonalForm: {
        ticketId: ''
      },
      signType: '', // 1 新增作业人 2 更换监护人
      changeGuardianForm: {
        staffId: '',
        taskId: '',
        ticketId: ''
      }
    }
  },
  methods: {
    // 禁止下拉刷新
    isPullDown(isPull) {
      //获取当前 Webview 窗口对象
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      const currentWebview = page.$getAppWebview && page.$getAppWebview()
      //根据状态值来切换禁用/开启下拉刷新
      currentWebview?.setStyle({
        pullToRefresh: {
          support: isPull,
          // style: plus.os.name === 'Android' ? 'circle' : 'default',
          style: 'circle'
        }
      })
    },
    styleSelector(option) {
      return 'level_' + option
    },
    initData() {
      this.pageNum = 1
      this.getlist()
    },
    reloadData() {
      this.isFinished = false
      this.loading = false
      this.addPersonalForm = {
        ticketId: '',
        reviewerSignatures: []
      }
      this.signType = ''
      this.changeGuardianForm = {
        reviewerSignature: '',
        staffId: '',
        taskId: '',
        ticketId: ''
      }
      this.initData()
    },

    async getlist() {
      if (this.isFinished || this.loading) {
        return
      }
      this.loading = true
      const { rows, total } = await getAcceptTicketList({
        pageNum: this.pageNum
      }).finally(() => {
        this.loading = false
      })

      rows.map((item) => {
        const nodePermissions = item.nodePermissions?.split(',') ?? []
        // 当前节点必须有暂停权限，监护人和节点审查人才能暂停和启动
        if (nodePermissions.includes(actNodePermissionEnum.PAUSE) && item.assignee === this.staffId) {
          item.canPauseOrStart = true
        }
        item.canAnalyse = [
          specialWorkTypeEnum.FIRE,
          specialWorkTypeEnum.LIMIT_SPACE,
          specialWorkTypeEnum.ELECTRIC
        ].includes(item.specialWorkType)
        return item
      })

      this.listData = this.pageNum === 1 ? rows : [...this.listData, ...rows]
      this.isFinished = this.listData.length >= total
      this.pageNum += 1
      uni.stopPullDownRefresh()
    },

    /**
     * @description 校验定位
     */
    async positionValidate(ticketId) {
      // true 不可以处理
      // false 可以处理
      /*
       * 0 未定义围栏 1 已到排查区域 4 忽略校验
       * */
      let { data } = await poiValid(ticketId)
      if (data.code === 0 || data.code === 1 || data.code === 4) {
        return false
      } else {
        this.$modal.showToast(data.title)
        return true
      }
    },

    /**
     * @description 根据不同的节点类型跳转对应的目标页面
     */
    async goPage(row, type, btnLabel) {
      let rew = null
      if (btnLabel !== '分析') {
        rew = await this.positionValidate(row.ticketId)
        console.log('r', rew)
      }

      if (rew) return

      let url = ''
      switch (type) {
        case 'check':
          url = '/pages/jobSlip/check/inspect'
          break
        case 'start':
          url = '/pages/jobSlip/spw-status/start'
          break
        case 'pause':
          url = '/pages/jobSlip/spw-status/pause'
          break
        default:
          break
      }
      uni.navigateTo({
        url: `${url}?nodeTaskId=${row.nodeTaskId}&ticketId=${row.ticketId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    async goAcceptance(row) {
      let rew = await this.positionValidate(row.ticketId)
      console.log('r', rew)

      if (rew) return

      uni.navigateTo({
        url: `/pages/jobSlip/execute/acceptance?ticketId=${row.ticketId}&nodeTaskId=${row.nodeTaskId}&specialWorkType=${row.workTypeFlag}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    // 添加分析数据
    goInspect(row) {
      uni.navigateTo({
        url: `/pages/jobSlip/execute/analyse?ticketId=${row.ticketId}&nodeTaskId=${row.nodeTaskId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          'callback:success': (data) => {
            if (data) {
              this.reloadData()
            }
          }
        }
      })
    },
    showSignature(row) {
      this.addPersonalForm.ticketId = row.ticketId
      this.signType = 1
      this.isPullDown(false)
      this.$refs.signature.open()
    },
    onSignatureSuccess() {
      this.isPullDown(true)
      if (this.signType == 1) {
        addWorkPersonal({
          ...this.addPersonalForm,
          signatureUrls: this.signatureUrl
        }).then((res) => {
          this.$modal.showToast('新增作业人员成功')
        })
      }
      if (this.signType == 2) {
        updateGuardian({
          ...this.changeGuardianForm,
          signatureUrls: this.signatureUrl
        }).then((res) => {
          this.$modal.showToast('更换监护人成功')
          this.reloadData()
        })
      }
    },
    userSelectorChange(obj) {
      if (!Object.keys(obj).length) {
        this.$modal.showToast('请选择监护人')
        return
      }
      this.changeGuardianForm.staffId = obj.value
      this.signType = 2
      this.isPullDown(false)
      this.$refs.signature.open()
    }
  }
}
</script>

<style lang="scss" scoped>
.cu-card-wrap {
  margin-bottom: 24rpx;
  position: relative;
}

.more-button {
  font-size: 28rpx;
  font-weight: 400;
  color: #999999;
  line-height: 60rpx;
  height: 60rpx;
}

.icon-more {
  width: 32rpx;
  height: 32rpx;
  vertical-align: sub;
}

.cu-card-wrap .footer-wrap .more-button {
  width: 60rpx;
  height: 60rpx;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-button-wrap {
  border-top: 1rpx solid #d5d7e3;
  display: flex;
  flex-wrap: wrap;
  padding-top: 10rpx;

  .status-button {
    border: 1rpx solid #88b4c4;
    color: #88b4c4;

    &.active {
      border: 1rpx solid #c87c32;
      color: #c87c32;
    }
  }
}

.affix {
  //width: 90px;
  height: 30px;
  position: absolute;
  top: 0;
  right: 0;
}

uni-image.affix-icon {
  height: 30px !important;
  width: 78px !important;
}

.popup-wrap {
  width: 650rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx 30rpx;

  .button-wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 150rpx;

    .button {
      width: 246rpx;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      text-align: center;
      font-size: 30rpx;
      display: block;
      margin: 0 12rpx;
    }

    .button-confirm {
      background: #454a5e;
      color: #ffffff;
    }

    .button-cancle {
      background: #e3e4eb;
      color: #454a5e;
    }
  }
}
</style>
